package com.dm.mcode.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Point;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;


import java.lang.reflect.Method;

public class HardwareManager {
    public static final int API_VERSION = Build.VERSION.SDK_INT;
    public static double screenInches = 0;

    /**
     * 获取DeviceId,如果获取不到，默认空字符串。
     */
    public static String getDeviceId(Context mContext) {
        String deviceId = null;
        // Requires READ_PHONE_STATE
        // Returns the unique device ID, for example, the IMEI for GSM and the
        // MEID or ESN for CDMA phones. Return null if device ID is not
        // available.
        // Requires Permission: READ_PHONE_STATE

        deviceId = ((TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
        if (deviceId == null) {
            // A 64-bit number (as a hex string) that is randomly generated on
            // the device's first boot and should remain constant for the
            // lifetime of the device. (The value may change if a factory reset
            // is performed on the device.)
            deviceId = Secure.getString(mContext.getContentResolver(), Secure.ANDROID_ID);
        }

        if (deviceId == null) {
            deviceId = "";
        }
        return deviceId;
    }

    /**
     * 获取设备macAddress信息,有的设备wifi开关未开启的话获取不到wifi值。如果获取不到，默认空字符串。
     *
     * @param mContext
     * @return
     */
    public static String getMacAddress(Context mContext) {
        // Requires READ_PHONE_STATE
        String macAddress = null;
        // android.permission.ACCESS_WIFI_STATE or comes as null
        WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
        if (wifiManager != null) {
            macAddress = wifiManager.getConnectionInfo().getMacAddress();
        }

        if (macAddress == null) {
            macAddress = "";
            openWifiForGetMac(mContext);
        }
        return macAddress;
    }

    /**
     * 打开wifi开关。（新华平板需要先打开wifi才能获取到mac）
     */
    public static void openWifiForGetMac(Context mContext) {
        // 获取wifi管理服务
        WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
        if (!wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
        }
    }

    /**
     * 关闭wifi开关。（新华平板需要先打开wifi才能获取到mac）
     */
    public static void closeWifiForGetMac(Context mContext) {
        // 获取wifi管理服务
        WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
        if (wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(false);
        }
    }

    /**
     * 获取宽高：pix
     *
     * @param act
     */
    @SuppressLint("NewApi")
    public static PhoneScreen getScreen(Activity act) {
        Display display = act.getWindowManager().getDefaultDisplay();
        int realWidth;
        int realHeight;

        if (Build.VERSION.SDK_INT >= 17) {
            // new pleasant way to get real metrics
            DisplayMetrics realMetrics = new DisplayMetrics();
            display.getRealMetrics(realMetrics);
            realWidth = realMetrics.widthPixels;
            realHeight = realMetrics.heightPixels;

        } else if (Build.VERSION.SDK_INT >= 14) {
            // reflection for this weird in-between time
            try {
                Method mGetRawH = Display.class.getMethod("getRawHeight");
                Method mGetRawW = Display.class.getMethod("getRawWidth");
                realWidth = (Integer) mGetRawW.invoke(display);
                realHeight = (Integer) mGetRawH.invoke(display);
            } catch (Exception e) {
                // this may not be 100% accurate, but it's all we've got
                realWidth = display.getWidth();
                realHeight = display.getHeight();
                Log.e("Display Info", "Couldn't use reflection to get the real display metrics.");
            }

        } else {
            // This should be close, as lower API devices should not have window
            // navigation bars
            realWidth = display.getWidth();
            realHeight = display.getHeight();
        }

        return new PhoneScreen(realWidth, realHeight);
    }

    /**
     * 获取屏幕物理尺寸
     *
     * @param act
     */
    @SuppressLint("NewApi")
    public static double getScreenSizeOfDevice2(Activity act) {
        Point point = new Point();
        act.getWindowManager().getDefaultDisplay().getRealSize(point);
        DisplayMetrics dm = act.getResources().getDisplayMetrics();
        double x = Math.pow(point.x / dm.xdpi, 2);
        double y = Math.pow(point.y / dm.ydpi, 2);
        double screenInches = Math.sqrt(x + y);
        Log.i("Display Info", "Screen inches : " + screenInches);
        return screenInches;
    }

    public static double getScreenSizeInInches(Activity act) {
        DisplayMetrics dm = new DisplayMetrics();
        act.getWindowManager().getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;
        int height = dm.heightPixels;
        int dens = dm.densityDpi;
        double wi = (double) width / (double) dens;
        double hi = (double) height / (double) dens;
        double x = Math.pow(wi, 2);
        double y = Math.pow(hi, 2);
        double screenInches = Math.sqrt(x + y);
        return screenInches;
    }

    /**
     * 获取系统参数
     *
     * @param context
     * @return
     */
    public static String[] getDeviceStrs(Context context) {
        //获取手机号码
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String deviceid = tm.getDeviceId();//获取智能设备唯一编号
        String te1 = tm.getLine1Number();//获取本机号码
        String imei = tm.getSimSerialNumber();//获得SIM卡的序号
        String imsi = tm.getSubscriberId();//得到用户Id
        String result[] = new String[4];
        result[0] = deviceid;
        result[1] = te1;
        result[2] = imei;
        result[3] = imsi;
        return result;
    }
}
